/**
* File Name: fork_anony_mmap.c
* Auther: Jichang
* Create Time: 2023年10月06日 星期五 15时41分28秒
* 创建匿名映射区
*/
#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<sys/mman.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<unistd.h>

int var = 100;

int main() {
	int *p;
	pid_t pid;
	int fd = open("/dev/zero", O_RDWR);

	//创建匿名映射区
	//p = (int *)mmap(NULL, 4, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
	//Unix
	p = (int *)mmap(NULL, 4, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
	if(p == MAP_FAILED) {
		perror("mmap error");
		exit(1);
	}
	close(fd);

	pid = fork();  //创建子进程
	if(pid == 0) {
		*p = 2000;   //写共享内存
		var = 1000;  //子进程修改
		printf("child, *p=%d, var=%d\n", *p, var);
	} else {
		sleep(1);   //等待子进程修改完毕
		printf("parent, *p=%d, var=%d\n", *p, var);//读取
		wait(NULL);

		int ret = munmap(p, 4); //释放映射区
		if(ret == -1) {
			perror("munmap error");
			exit(1);
		}
	}

	return 0;
}


